package cn.gzmli.dtt.common.controll;


import cn.gzmli.dtt.common.annotation.Comment;
import cn.gzmli.dtt.common.annotation.Ignore;
import cn.gzmli.dtt.common.annotation.Privilege;
import cn.gzmli.dtt.common.entity.*;
import cn.gzmli.dtt.common.utils.Constant;
import cn.gzmli.dtt.common.service.MenuService;
import cn.gzmli.dtt.common.service.PermissionService;
import cn.gzmli.dtt.common.service.RoleService;
import cn.gzmli.dtt.common.utils.BaseController;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang.ArrayUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * Title:PermissionController 
 * Description: 权限管理接口
 * @author:superKing_zhanglh
 * @date 2018年4月3日
 */
@Controller
@RequestMapping("/permission")
public class PermissionController implements BaseController<Permission> {

    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private MenuService menuService;


    @Override
    @RequestMapping("/list")
    @ResponseBody
    @Comment("获取权限列表")
    public Result list() throws Exception {
        return new Result(Constant.SUCCESS, "获取权限列表成功", this.permissionService.getAll());
    }

    @Override
    @RequestMapping("/listByCondition")
    @ResponseBody
    @Comment("获取权限列表")
    public Result listByCondition(HttpServletRequest request, PageInfo pageInfo) throws Exception {
        List<Map<String, Object>> data = permissionService.getByCondition(request, pageInfo);
        return new Result(Constant.SUCCESS, "获取权限列表成功", data, pageInfo);
    }

    @Override
    @RequestMapping("/get")
    @ResponseBody
    @Comment("获取权限信息")
    public Result get(Integer id) throws Exception {
        return new Result(Constant.SUCCESS, "获取权限信息成功", this.permissionService.get(id));
    }

    @Override
    @RequestMapping("/getByCondition")
    @ResponseBody
    @Comment("获取权限信息")
    public Result getByCondition(HttpServletRequest request) throws Exception {
        Map<String, String> condition = new HashMap<>();
        return new Result(Constant.SUCCESS, "获取权限信息成功", this.permissionService.getByCondition(condition));
    }

    @Override
    @RequestMapping("/save")
    @ResponseBody
    @Comment("新增权限信息")
    @Privilege("/permission/save")
    public Result save(Permission permission) throws Exception {
        //去空格
        permission.setPermission_code(permission.getPermission_code().trim());

        Map<String, String> condition = new HashMap<>();
     condition.put("permission_name", "="+ StrUtil.wrap(permission.getPermission_name(), "'", "'"));
     Permission p = permissionService.getByCondition(condition);
     if(p !=null){
        return new Result(Constant.FAIL,"该权限名称已存在");
      }
     condition = new HashMap<>();
     condition.put("permission_code", "="+ StrUtil.wrap(permission.getPermission_code(), "'", "'"));
	 Permission per = permissionService.getByCondition(condition);
	 if(per !=null){
		 return new Result(Constant.SUCCESS, "此权限url已存在");
	 }
	 //设置pId
	 DetachedCriteria ctirteria = DetachedCriteria.forClass(Permission.class);
	 ctirteria.add(Restrictions.eq("menu_id", permission.getMenu_id()));
	 List<Permission> list = permissionService.getByCondition(ctirteria);
	 
	 if(list != null && list.size() > 0){
		 per = list.get(0);
		 permission.setpId(per.getpId());
	 }else{
		 //插入当前权限的pId
		 Menu menu = menuService.get(permission.getMenu_id());
		 Permission perm = new Permission();
		 perm.setpId(0);
		 perm.setMenu_id(1);//所属菜单
		 perm.setPermission_name(menu.getName());
		 //保存当前权限的上级菜单
		 Permission savePerm = permissionService.save(perm);
		 permission.setpId(savePerm.getId());//插入当前权限的pId
	 }
	 
	 
	//保存权限信息
	 permissionService.save(permission);
     return new Result(Constant.SUCCESS, "新增权限信息成功");
    }

    @Override
    @RequestMapping("/update")
    @ResponseBody
    @Comment("修改权限信息")
    @Privilege("/permission/update")
    public Result update(Permission permission) throws Exception {
        if(permission == null){
            return new Result(Constant.FAIL, "数据不能为空！");
        }
        //如果权限已经被角色绑定了则不让修改
        List<Map<String, Object>> listsRolePermissions = roleService.getRolePermissionsByContion(permission.getId());
        if(listsRolePermissions != null){
            return new Result(Constant.FAIL, "该权限已经被绑定过，不能修改！");
        }

        //如果沒有修改，则不用更新
    	Permission per = permissionService.get(permission.getId());
    	if(per.getMenu_id() == permission.getMenu_id()
    			&& per.getPermission_code() == permission.getPermission_code()
    			&& per.getPermission_name() == permission.getPermission_name()){
    		return new Result(Constant.FAIL, "未做改变！");
    	}
    	//判断权限名称是否重复
         Map<String, String> condition = new HashMap<>();
         condition.put("permission_name", "="+ StrUtil.wrap(permission.getPermission_name(), "'", "'"));
         Permission perm = permissionService.getByCondition(condition);
         
         //判断权限url是否重复
         Map<String, String> condition2 = new HashMap<>();
         condition2.put("permission_code", "="+ StrUtil.wrap(permission.getPermission_code(), "'", "'"));
         Permission perm2 = permissionService.getByCondition(condition);
         
         if(perm != null && perm.getId() != permission.getId()){
        	 if(permission.getPermission_name().equals(perm.getPermission_name())){
        		 return new Result(Constant.FAIL, "该权限名称已存在！");
        	 } 
         }
         if(perm2 != null && perm2.getId() != permission.getId()){
        	 if(permission.getPermission_code().equals(perm.getPermission_code())){
        		 return new Result(Constant.FAIL, "该权限url已存在！");
        	 } 
         }

         //更新pId
         DetachedCriteria ctirteria = DetachedCriteria.forClass(Permission.class);
    	 ctirteria.add(Restrictions.eq("menu_id", permission.getMenu_id()));
         List<Permission> lists = permissionService.getByCondition(ctirteria);

    	 if(lists != null && lists.size() > 0){
             per = lists.get(0);
    		 permission.setpId(per.getpId());
    	 }else{
    		 //插入当前权限的pId
    		 Menu menu = menuService.get(permission.getMenu_id());
    		 Permission perm3 = new Permission();
    		 perm3.setpId(0);
    		 perm3.setMenu_id(1);//所属菜单
    		 perm3.setPermission_name(menu.getName());
    		 //保存当前权限的上级菜单
    		 Permission savePerm = permissionService.save(perm3);
    		 permission.setpId(savePerm.getId());//插入当前权限的pId
    	 }
         
        this.permissionService.update(permission);
        return new Result(Constant.SUCCESS, "修改权限信息成功");
    }

    @Override
    @RequestMapping("/delete")
    @ResponseBody
    @Comment("删除权限信息")
    @Privilege("/permission/delete")
    public Result delete(Permission permission) throws Exception {
    	 List<Role> list =  roleService.getAll();
    	 boolean flag =false;
    	 for(Role r : list){
    		 String[] permissions = r.getPermissionIDS().split(",");

             flag = ArrayUtils.contains(permissions,permission.getId()+"");
    		 if(flag){
    			 break;
    		 }
    	 }
    	 if(flag){
    		 return new Result(Constant.FAIL, "该权限有角色关联，不能删除");
    	 }
        this.permissionService.delete(permission);
        return new Result(Constant.SUCCESS, "删除权限信息成功");
    }

    @RequestMapping("/error")
    @ResponseBody
	public Result error(){
		return new Result(Constant.FAIL,"你没有该权限操作");
	}

    @RequestMapping(value = "/listPermissionMenu")
    @ResponseBody
    @Ignore
	public Result listPermissionMenu(HttpServletRequest request, PageInfo pageInfo) throws Exception {
		return new Result(Constant.SUCCESS, "获取角色菜单成功", permissionService.getTree(request));
	}
    
    @RequestMapping("/listTree")
    @ResponseBody
    @Ignore
    public Result listTree(HttpServletRequest request) throws Exception {
        return new Result(Constant.SUCCESS, "获取权限列表成功", this.permissionService.getTree(request));
    }

	@Override
	public Result lists(HttpServletRequest request, PageInfo pageInfo) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
